package com.qili.interceptor;

import com.qili.base.entity.CurrentUser;
import com.qili.core.shiro.Principal;
import com.qili.entity.sys.SysUser;
import com.qili.service.SysUserService;
import com.qili.util.CustomUsernamePasswordToken;
import lombok.extern.log4j.Log4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author liuyang
 * @date 2020/12/30
 * @description
 */
@Log4j
public class SessionInterceptor implements HandlerInterceptor {

    @Resource
    SysUserService sysUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        System.out.println(request.getContextPath());
        Subject subject = SecurityUtils.getSubject();
        //判断用户是通过记住我功能自动登录,此时session失效
        if(!subject.isAuthenticated() && subject.isRemembered()){
            CurrentUser sysUser = (CurrentUser )subject.getPrincipals().getPrimaryPrincipal();
            try {
//                CustomUsernamePasswordToken token = new CustomUsernamePasswordToken(sysUser.getUsername().trim(), sysUser.getPassword(), "UserL","rememberMe");
                Object currentPrincipal = subject.getSession().getAttribute("currentPrincipal");
                if(currentPrincipal == null){
                    sysUserService.setMenuAndRoles(sysUser.getUsername());
                }
//                subject.login(token);
//                if (subject.isAuthenticated()) {
//                    token.getUsername();
//                    return true;
//                }else{
//                    response.sendRedirect(request.getContextPath()+"/login");
//                    return false;
//                }
            }catch (Exception e){
                //自动登录失败,跳转到登录页面
                response.sendRedirect(request.getContextPath()+"/login");
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        log.info("---afterCompletion---");
    }


}
